package utilitarios;

import java.util.Random;

public class Cpf {
    
    public static String geraCpf(){
        Random rd = new Random();
        String digitos = "";
        for(int i = 0; i < 9; i++){
            digitos += String.valueOf(rd.nextInt(10));
        }
        
        return montaCpf(digitos);
    }
    
    public static boolean verificaCpf(String cpf){
        
        cpf = cpf.replace(".", "").replace("-", "");
        if(verificaNumIguais(cpf)){
            return false;
        }
        String[] sub = new String[2];
        sub[0] = cpf.substring(0, 9);
        sub[1] = cpf.substring(9, 11);
        
        String cpfGerado = montaCpf(sub[0]);
//        System.out.println("cpf: "+cpf+ " cpf gerado: "+cpfGerado.replace(".", "").replace("-", ""));
        if(cpf.equals(cpfGerado.replace(".", "").replace("-", ""))){
//            System.out.println("TRUE");
            return true;
        }
//        System.out.println("FALSE");
        return false;
    }
    
    private static String montaCpf(String num){
        String cpf  = num+digitoVerificador(somaDigitos(num));
        if(cpf.toCharArray().length == 11){
            return insereCaracteresEspeciais(cpf);
        }else{
            return montaCpf(cpf);
        }
    }
    
    private static int somaDigitos(String num) {
        char[] cpf = num.toCharArray();
        int tot = 0;
        int cont = cpf.length+1;
        for (int i = 0; i < cpf.length; i++) {
            tot += Integer.parseInt(String.valueOf(cpf[i])) * cont;
            cont--;
        }
//        System.out.println(tot+" % 11 = "+tot % 11);
        return tot;
    }
    
    private static int digitoVerificador(int tot){
        int resto;
        resto = tot%11;
        if(resto < 2){
            return 0;
        }else{
            return 11 - resto;
        }
    }
    
    private static String insereCaracteresEspeciais(String num){
        char[] cpf = num.toCharArray();
        String c = "..-";
        char[] caracter = c.toCharArray();
        
        char[] cpfNovo = new char[cpf.length+caracter.length];
        int j = 0;
        int k = 0;
        for(int i = 0; i < cpfNovo.length; i++){
            if(i == 3 || i == 7 || i == 11){
                cpfNovo[i] = caracter[j];
                j++;
            }else{
                cpfNovo[i] = cpf[k];
                k++;
            }
        }
        return String.valueOf(cpfNovo);
    }
    
    private static boolean verificaNumIguais(String num){//verifica se todos numeros sao ifuais
        char[] nums = num.toCharArray();
        for(int i = 0; i < nums.length-1; i++){
            if(nums[i] != nums[i+1]){
                return false;
            }
        }
        return true;
    }
}
